import sun.reflect.generics.tree.Tree;

public class Main {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2, new TreeNode(4), new TreeNode(5));
        root.right = new TreeNode(3, new TreeNode(6), null);
        Solution s = new Solution();
        System.out.println(s.countNodes(root));
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

//二分查找
class Solution {
    public int countNodes(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int maxDepth = getMaxDepth(root);
        int numLastLevel = countLastLevel(root, maxDepth);
        return numLastLevel + (1 << (maxDepth - 1)) - 1;
    }

    int countLastLevel(TreeNode root, int maxDepth) {
        TreeNode cur = root;
        int curDepth = 1;
        int numLastLevel = 1 << (maxDepth - 1);
        while (curDepth <= maxDepth) {
            int curMaxDepth =  curDepth + getMaxDepth(cur.right);
            if (curMaxDepth < maxDepth) {
                cur = cur.left;
                numLastLevel -= 1 << (maxDepth - curDepth - 1);
            } else {
                cur = cur.right;
            }
            curDepth++;
        }
        return numLastLevel;
    }

    int getMaxDepth(TreeNode root) {
        int count = 0;
        while (root != null) {
            root = root.left;
            count++;
        }
        return count;
    }
}

//官方题解二分查找，二进制数
class Solution1 {
    public int countNodes(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int maxDepth = getMaxDepth(root);
        int min = 1 << (maxDepth - 1);
        int max = (1 << maxDepth) - 1;
        int ans = min;
        while (min <= max) {
            int mid = (min + max) / 2;
            if (exists(root, maxDepth, mid)) {
                ans = mid;
                min = mid + 1;
            } else {
                max = mid - 1;
            }
        }
        return ans;
    }

    boolean exists(TreeNode root, int maxDepth, int n) {
        int depth = 1;
        int bit = 1 << (maxDepth - 2);
        while (root != null && depth < maxDepth) {
            if ((bit & n) > 0) {
                root = root.right;
            } else {
                root = root.left;
            }
            bit >>= 1;
            depth++;
        }
        return root != null;
    }

    int getMaxDepth(TreeNode root) {
        int count = 0;
        while (root != null) {
            root = root.left;
            count++;
        }
        return count;
    }
}